import api from '../../../http/api.js'
export default {
	data() {
		return {
			formData: {
				accountNumber: '',
				password: '',
				invitationCode: ''
			},

			errors: {
				accountNumber: '',
				password: '',
				invitationCode: ''
			}
		}
	},
	methods: {
		// 验证账号
		validateAccountNumber() {
			const accountNumber = this.formData.accountNumber;
			if (!accountNumber) {
				this.errors.accountNumber = '账号/手机号不能为空';
			} else if (accountNumber.length < 6 || !/[a-zA-Z]/.test(accountNumber) || !/[0-9]/.test(accountNumber)) {
				this.errors.accountNumber = '请填写正确账号格式';
			} else {
				this.errors.accountNumber = '';
			}
		},
		// 验证密码
		validatePassword() {
			const password = this.formData.password;
			this.errors.password = '';
			if (!password) {
				this.errors.password = '密码不能为空';
				return;
			}
			if (password.length < 6) {
				this.errors.password = '密码长度至少6位';
				return;
			}
		},
		// 验证邀请码
		validateInvitationCode() {
			const invitationCode = this.formData.invitationCode;
			if (!invitationCode) {
				this.errors.invitationCode = '邀请码不能为空';
			} else {
				this.errors.invitationCode = '';
			}
		},
		//注册账号
		register() {
			// 提交前的最终验证
			this.validateAccountNumber();
			this.validatePassword();
			this.validateInvitationCode();
			if (this.isFormValid) {
				uni.showLoading({
					title: '注册中...',
					mask: true
				});
				api.getregister({
					"username": this.formData.accountNumber,
					"password": this.formData.password,
					"invite_code": this.formData.invitationCode
				}).then(res => {
					if(res.code==1){
						uni.$emit('refreshData', { key: res.data.userinfo.username }); // 发送事件
						uni.navigateBack({ delta: 1 });
					}else{
						uni.showToast({
							title:res.msg ,
							icon: 'none'
						})
					}
				}).catch(err => {
					this.handleRegisterError(err)
				}).finally(fer => {
					uni.hideLoading();
				})

			} else {
				uni.showToast({
					title: '请填写完整注册信息',
					icon: 'none',
					duration:3000
				});
			}

		},
		// 错误处理
		handleRegisterError(error) {
			console.error('注册错误:', error);
			// 特定错误码处理
			if (error.code === 'PHONE_EXIST') {
				return uni.showToast({
					title: '帐号已注册',
					icon: 'none'
				});
			}

			// 网络错误处理
			if (error.code === 'NETWORK_ERROR') {
				return uni.showToast({
					title: '网络不稳定，请重试',
					icon: 'none'
				});
			}

			// 通用错误提示
			uni.showToast({
				title: error.msg || '注册失败，请重试',
				icon: 'none'
			});
		},
	},
	computed: {
		isFormValid() {
			return Object.values(this.errors).every(error => !error) &&
				Object.values(this.formData).every(val => val !== '');
		}
	},
}